/**
 *
 * Created by levy on 16/2/12.
 */
log = function(msg){
    console.log(msg);
}

/*通用函数*/
//添加样式
function addClass(ele,newClass){
    if(!ele.className){
        ele.className = newClass;
    }
    else{
        ele.className += " " + newClass;
    }
}

//在xx元素之后插入,用到了parentNode,nextSibling两个关键api
function insertAfter(newEle, targetEle){
    var parent = targetEle.parentNode;
    if(parent.lastChild == targetEle){
        parent.appendChild(newEle);
    }
    else{
        parent.insertBefore(newEle, targetEle.nextSibling);
    }
}

//添加一个window.onload时要执行的函数
function addLoadEvent(func){
    var oldOnload = window.onload;
    if(typeof window.onload != 'function'){
        window.onload = func;
    }
    else{
        window.onload = function(){
            oldOnload();
            func();
        }
    }
}

function highlightPage(){
    if(!document.getElementsByTagName) return false;

    var location = window.location.href;
    //var url = location.split('/');
    //var page = url[url.length - 1];

    var navs = document.getElementsByTagName('nav');
    if(navs.length < 1) return false;

    var links = navs[0].getElementsByTagName('a');
    for(var i = 0; i < links.length; i++){
        var href = links[i].getAttribute('href');
        if(href && location.indexOf(href) > -1){
            //注意函数入参如果是字符串,必须用引号包起来
            addClass(links[i],'here');
            //以页面的文件名作为id,因为我认为页面文字可能会改,但文件名不常改
            var id = href.split('.')[0];
            document.body.setAttribute('id',id);
            break;
        }
    }
}

function moveElement(eleId,final_x,final_y,interval){
    if(!document.getElementById) return false;
    if(!final_x) final_x = 0;
    if(!final_y) final_y = 0;
    if(!interval) interval = 10;

    var ele = document.getElementById(eleId);
    if(!ele) return false;
    if(ele.movement) clearTimeout(ele.movement);

    var left = ele.style.left;
    var top = ele.style.top;
    if(!left) left = 0;
    if(!top) top = 0;

    var x = parseInt(left);
    var y = parseInt(top);
    if(x == final_x && y == final_y) return true;

    var distX = Math.ceil(Math.abs(final_x - x) / 10);
    var distY = Math.ceil(Math.abs(final_y - y) / 10);
    if(x < final_x){
        x += distX;
    }
    if(x > final_x){
        x -= distX;
    }
    if(y < final_y){
        y += distY;
    }
    if(y > final_y){
        y -= distY;
    }

    ele.style.left = x + 'px';
    ele.style.top = y + 'px';

    //很容易出错:字符串拼接,想想结果是怎样的?最终生成的是被一对引号包起来的字符串啊
    //则里面的eleId=msg,则在下个函数调用里,就变成了直接传#msg的元素了!
    //所以这个拼接字符串时,必须把单引号也拼上去
    var repeat = "moveElement('" + eleId + "'," + final_x + "," + final_y + "," + interval + ")";
    //log(repeat)

    ele.movement = setTimeout(repeat,interval);
}

function prepareSlideShow(){
    if(!document.getElementById || !document.getElementsByTagName || !document.createElement) return false;
    var intro = document.getElementById('intro');
    if(!intro) return false;

    var preview = document.createElement('img');
    preview.setAttribute('id','preview');
    preview.setAttribute('src','../images/slideshow.gif');
    preview.setAttribute('alt','a glimpse of what awaits you');

    var slideShow = document.createElement('div');
    slideShow.setAttribute('id','slideshow');
    slideShow.appendChild(preview);
    insertAfter(slideShow,intro);

    //move picture
    var links = intro.getElementsByTagName('a');
    var dist;
    for(var i = 0; i < links.length; i++){
        links[i].onmouseover = function(){
            dist = this.getAttribute('href');
            log(dist)
            if(dist.indexOf('index') > -1){
                moveElement('preview',0,0,5);
            }
            if(dist.indexOf('about') > -1){
                moveElement('preview',-150,0,5);
            }
            if(dist.indexOf('photos') > -1){
                moveElement('preview',-300,0,5);
            }
            if(dist.indexOf('live') > -1){
                moveElement('preview',-450,0,5);
            }
            if(dist.indexOf('contact') > -1){
                moveElement('preview',-600,0,5);
            }
        }
    }
}

/**
 * 这里有一个易忽略点:不能想当然的认showPic函数会正常返回:
 * 也许js未被禁用,但点击链接什么也没有发生,这样的代码是不能平稳退化的.
 * @param pic
 * @returns {boolean}
 */
function showPic(pic){
    var placeholder = document.getElementById('placeholder');
    if(!placeholder) return false;

    //改变图片
    var href = pic.getAttribute('href');
    placeholder.setAttribute('src', href);

    //改变文本
    var desc = document.getElementById('description');
    //要有文本才有childNodes[0],也可写作firstChild, lastChild
    if(desc){
        var title = pic.getAttribute('title');
        if(title)
            desc.firstChild.nodeValue = title;
    }
    return true;
}

function prepareGallery(){
    if(!document.getElementById || !document.getElementsByTagName)
        return false;
    //这样的话,图片删除掉,页面上找不到id为imageGallery的元素,代码也不会出错
    if(!document.getElementById('imageGallery'))
        return false;
    //必要的检查之后,可以安心写核心功能了
    var gallery = document.getElementById('imageGallery');
    var links = gallery.getElementsByTagName('a');
    for(var i = 0; i < links.length; i++){
        links[i].onclick = function(){
            //this 表示与onclick关联的那个元素
            //阻止a标签默认的href事件
            return !showPic(this);
            //return false;
        }
    }

}

//动态创建图片显示地及文本说明
function preparePlaceholder(){
    if(!document.createElement || ! document.createTextNode) return false;
    if(!document.getElementById) return false;

    var gallery = document.getElementById('imageGallery');
    if(!gallery) return false;

    var img = document.createElement('img');
    img.setAttribute('id','placeholder');
    img.setAttribute('src','images/placeholder.gif');
    img.setAttribute('alt','Image Gallery');

    var desc = document.createElement('p');
    desc.setAttribute('id','description');
    var desc_txt = document.createTextNode('choose an image with mouse or keyboard');
    desc.appendChild(desc_txt);

    //HTML-DOM
    //document.body.appendChild(img);
    //document.body.appendChild(desc);

    //在xx元素之前插入parentNode.insertBefore(new,target);
    //gallery.parentNode.insertBefore(img,gallery);
    //gallery.parentNode.insertBefore(desc,gallery);

    insertAfter(desc,gallery);
    insertAfter(img,desc);
}

function hideSection(){
    if(!document.getElementById || !document.getElementsByTagName) return false;

    var articles = document.getElementsByTagName('article');
    if(articles.length == 0) return false;

    var navs = articles[0].getElementsByTagName('nav');
    if(navs.length == 0) return false;

    var links = navs[0].getElementsByTagName('a');
    for(var i = 0; i < links.length; i++){
        var href = links[i].getAttribute('href');
        if(!href ) continue;

        var array = href.split('#');
        if(array.length == 1) continue;

        var id = array[1];
        document.getElementById(id).style.display = 'none';

        //又是经典的闭包作用域问题
        links[i].sectionId = id;// 把id放到links[i]对象上,这是dom编程技术的解决方案
        links[i].onclick = function(){
            showSection(this.sectionId);
            return false; //阻止href的默认行为
        };


        //老办法,构建一个自运行带参匿名函数,让onclick函数引用匿名函数的入参
        //这是good part的办法
        //老办法永远能用,但新方法看起来简洁明了啊.还是用新方法吧
        //(function(id){
        //    links[i].onclick = function(){
        //        log(id)
        //    }
        //})(id)
    }
}

function showSection(id){
    var sections = document.getElementsByTagName('section');
    if(sections.length == 0) return false;
    for(var i = 0; i < sections.length; i++){
        if(id == sections[i].getAttribute('id')){
            sections[i].style.display='block';
        }
        else{
            sections[i].style.display='none';
        }
    }
}

function displayAbbr(){
            if(!document.getElementsByTagName ||
               !document.createElement ||
               !document.createTextNode)
                return false;
            var article = document.getElementsByTagName('article')[0];
            var abbrs = article.getElementsByTagName('abbr');

            var dl = document.createElement('dl');

            for(var i = 0; i < abbrs.length; i++){
                var abbr = abbrs[i];
                //IE6 地雷
                if(abbr.childNodes.length < 1) continue;

                var key = abbr.firstChild.nodeValue;
                var value = abbr.getAttribute('title');
                //log(key + '-' + value);

                var dt = document.createElement('dt'),
                    dd = document.createElement('dd'),
                    dt_text = document.createTextNode(key),
                    dd_text = document.createTextNode(value);
                dt.appendChild(dt_text);
                dd.appendChild(dd_text);

                dl.appendChild(dt);
                dl.appendChild(dd);
            }
            //IE6 地雷
            if(dl.childNodes.length < 1) return false;

            var h3 = document.createElement('h3'),
                h3_text = document.createTextNode('缩略语列表');
            h3.appendChild(h3_text);

            article.appendChild(h3);
            article.appendChild(dl);
        }

function displayLoading(ele){
    if(!ele) ele = document.getElementsByTagName('article')[0];
    if(!ele) return;

    while(ele.hasChildNodes()){
        ele.removeChild(ele.lastChild);
    }

    var img = document.createElement('img');
    img.setAttribute('src','../images/loading.gif');
    img.setAttribute('alt','loading');
    ele.appendChild(img);
}

function prepareFrom(){
    var forms = document.forms;
    for(var i = 0; i < forms.length; i++){
        var form = forms[0];
        form.onsubmit = function(){
           displayLoading();
           return false;
        }
    }
}

window.onload = function(){
    //every page
    highlightPage();

    //index
    prepareSlideShow();

    //about
    hideSection();

    //photos
    preparePlaceholder();
    prepareGallery();

    //live
    displayAbbr();

    //contact
    prepareFrom();
}
